package com.swingson.componentprocessor.impl;

import com.swingson.SwingsonGui;
import com.swingson.componentprocessor.BaseProcessor;
import com.swingson.jsonparser.JsonObject;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

public class JMenuProcessor extends BaseProcessor {

    private boolean hasNestedMenu(JsonObject currentMenuItem) {
        if (currentMenuItem.getElementByName("jmenu") != null) {
            return true;
        }
        return false;
    }
    
    @Override
    public JComponent createComponent(JsonObject jsonElement, JComponent parent, SwingsonGui gui) {
        if(parent instanceof JMenu || parent instanceof JMenuBar || parent instanceof JPopupMenu){
            if(hasNestedMenu(jsonElement)){
                return new JMenu();
            }else{
                return new JMenuItem();
            }
        }

        JMenuBar panel = new JMenuBar();
        return panel;
    }

    @Override
    public void addCompomentToThis(Container parent, Component child, Object layoutParameter) {
    }

    @Override
    public CustomAddToParentStrategy getCustomAddToParentStategy() {
        return new CustomAddToParentStrategy() {

            @Override
            public void addCompomentToParent(final Container parent, final Component child, Object layoutParameter) {
                if (child instanceof JMenuBar) {
                    Window parentWindow = SwingUtilities.getWindowAncestor(parent);
                    if (parentWindow instanceof JFrame) {
                        ((JFrame) parentWindow).setJMenuBar((JMenuBar) child);
                    } else if (parentWindow instanceof JDialog) {
                        ((JDialog) parentWindow).setJMenuBar((JMenuBar) child);
                    }
                }else{
                    parent.add(child);
                }
            }
        };
    }

    @Override
    public Class[] getProcessingClass() {
        return new Class[]{JMenuBar.class, JMenu.class, JMenuItem.class};
    }
}
